<!--
 * @Descripttion: 本地供应商商品管理（商品上架？）
 * @version:
 * @Author: 赵致喜
 * @Date: 2020-10-12 11:23:14
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-20 09:39:38
-->
<template>
  <div>
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      size="mini"
      label-width="140px"
    >
      <el-row :gutter="10">
        <el-col :span="8">
          <el-card class="box-card">
            <el-tree
              :data="resourceArray"
              default-expand-all
              node-key="id"
              highlight-current
              check-on-click-node
              :props="initProps"
              @node-click="clickNode"
            ></el-tree>
          </el-card>
        </el-col>
        <el-col :span="16">
          <el-card class="box-card">
            <el-scrollbar ref="scroll" style="overflow-x: hidden">
              <el-col :span="12">
                <el-form-item label="商品编号sku" prop="sku">
                  <el-input
                    :disabled="skuShow"
                    v-model="formData.sku"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格型号" prop="typeNo">
                  <el-input
                    v-model="formData.typeNo"
                    :disabled="showFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品牌名称" prop="brandName">
                  <div class="set-flex">
                    <el-input
                      v-model="formData.brandName"
                      :disabled="true"
                    ></el-input>
                    <el-button
                      @click="openDialogBrand('', true)"
                      v-if="!showFlag"
                      >请选择</el-button
                    >
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input
                    v-model="formData.goodsName"
                    :disabled="showFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="进口标识" prop="isImport">
                  <el-radio-group
                    v-model="formData.isImport"
                    :disabled="showFlag"
                  >
                    <el-radio label="国产">国产</el-radio>
                    <el-radio label="进口">进口</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生产地" prop="goodsArea">
                  <el-input
                    v-model="formData.goodsArea"
                    :disabled="showFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="未税单价(元)" prop="initExcludeTaxPrice">
                  <el-input
                    v-model="formData.initExcludeTaxPrice"
                    :disabled="showFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
			  <el-col :span="12">
			    <el-form-item label="税率" prop="taxRate">
			      <el-select v-model="formData.taxRate" :disabled="showFlag">
					  <el-option value="3">3</el-option>
					  <el-option value="6">6</el-option>
					  <el-option value="9">9</el-option>
					  <el-option value="13">13</el-option>
				  </el-select>
			    </el-form-item>
			  </el-col>
              <el-col :span="12">
                <el-form-item label="市场价格（元）" prop="agreementPrice">
                  <el-input
                    v-model="formData.agreementPrice"
                    :disabled="showFlag"
                    autocomplete="off"
                    @keyup.native="
                      formData.agreementPrice = formData.agreementPrice.replace(
                        /^\D*(\d*(?:\.\d{0,2})?).*$/g,
                        '$1'
                      )
                    "
                  ></el-input> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="计量单位" prop="saleUnit">
                  <el-input
                    v-model="formData.saleUnit"
                    :disabled="showFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="库存" prop="goodsStock">
                  <el-input-number
                    :min="0"
                    :max="99999999"
                    v-model="formData.goodsStock"
                    :disabled="goodsStockShow"
                  ></el-input-number>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="开始生产日期" prop="produceDate">
                  <el-date-picker
                    class="produce-date"
                    v-model="formData.produceDate"
                    type="date"
                    placeholder="选择日期"
                    :disabled="showFlag"
                  >
                  </el-date-picker> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="商品重量（千克）" prop="goodsWeight">
                  <el-input
                    v-model="formData.goodsWeight"
                    :disabled="showFlag"
                    autocomplete="off"
                    @keyup.native="
                      formData.goodsWeight = formData.goodsWeight.replace(
                        /^\D*(\d*(?:\.\d{0,2})?).*$/g,
                        '$1'
                      )
                    "
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">

              </el-col>
              <el-col :span="24">
                <el-form-item label="包装方式" prop="packing">
                  <el-input
                    type="textarea"
                    show-word-limit
                    maxlength="1000"
                    v-model="formData.packing"
                    :disabled="showFlag"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="简单配置" prop="goodsParam">
                  <el-input
                    type="textarea"
                    show-word-limit
                    maxlength="1000"
                    v-model="formData.goodsParam"
                    :disabled="showFlag"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="主要图片上传" prop="mainFiles">
                  <el-input style="display:none" v-model="formData.mainFiles"></el-input>
                  <el-upload
                    :class="{'limited':showFlag||(mainFileList&&mainFileList.length>=1)}"
                    list-type="picture-card"
                    :action="fileUrl"
                    :data="{ fileType: 14 }"
                    :on-preview="handlePreview"
                    :on-remove="mainHandleRemove"
                    :before-remove="beforeRemove"
                    :on-success="mainHandleAvatarSuccess"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload"
                    :headers="fileHeaders"
                    :limit="1"
                    :on-exceed="handleExceed1"
                    :file-list="mainFileList"
                    :disabled="showFlag"
                  >
                    <i class="el-icon-plus"></i>
                    <div slot="tip" class="el-upload__tip">
                      <p>
                        请上传1个图片，图片格式要求jpg/png格式，且不超过500kb
                      </p>
                    </div>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="一般图片上传" prop="files">
                  <el-upload
                    ref="upload"
                    :http-request="uploadFile"
                    :class="{'limited':showFlag||(fileList&&fileList.length>=10)}"
                    list-type="picture-card"
                    :action="fileUrl"
                    :data="{ fileType: 14 }"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    :on-change="handleChange"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload"
                    :headers="fileHeaders"
                    :file-list="fileList"
                    :disabled="showFlag"
                    :auto-upload="false"
                    :multiple = true
                  >
                      <i class="el-icon-plus"></i>
                    <template v-if="!showFlag && fileData.length > 0">
                      <div slot="tip" class="el-upload__tip">
                        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
                        <p>只能上传jpg/png文件，且不超过500kb，最多可上传10个图片</p>
                      </div>
                    </template>
                  </el-upload>
                  <el-input style="display:none" v-model="formData.files"></el-input>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="" />
                  </el-dialog>
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item label="商品介绍" class="products">
                  <div class="">
                    <el-upload
                      :http-request="uploadFile"
                      class="uploadImage"
                      :action="fileUrl"
                      :data="{ fileType: 14 }"
                      :headers="fileHeaders"
                      accept=".jpg,.jpeg,.png,.gif"
                      multiple
                      :file-list="goodsDescFileList"
                      :on-remove="editorHandleRemove"
                      :before-upload="beforeAvatarUpload"
                      :on-change="editorHandleChange"
                      :on-success="handleImgSuccess"
                      :on-error="handleImgError"
                      :disabled="showFlag"
                    >
                      <template v-if="!showFlag && fileDataEditor.length > 0">
                        <div slot="tip" class="el-upload__tip">
                          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUploadEditor">上传到服务器</el-button>
<!--                          <p>只能上传jpg/png文件，且不超过500kb，最多可上传10个图片</p>-->
                        </div>
                      </template>

                    </el-upload>
                    <div class="edit-box" v-loading="loading">
                      <quill-editor
                        ref="text"
                        v-model="formData.goodsIntroduce"
                        class="myQuillEditor"
                        :options="editorOption"
                        :disabled="showFlag"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="主属性：">

                </el-form-item>
              </el-col>
              <p v-for="(item, i) in formData.goodsPropertyList" :key="i">
                <el-col :span="12">
                  <el-form-item :label="item.key"
                  :prop="'goodsPropertyList.' + i + '.value'"
                  :rules="[
                      { required: true, message: `请输入${item.key}`, trigger: 'blur' }
                    ]">
                    <el-input
                      v-model="item.value"
                      :disabled="showFlag"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </p>
            </el-scrollbar>
            <div class="putawayt-action" v-if="!goodsStockShow">
              <el-button type="primary" @click="saveOrUpdateProducts"
                >保存</el-button
              >
              <el-button type="primary" v-if="!showFlag" @click="submitProducts">提交</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      title="请选择品牌名称"
      :visible.sync="dialogBrand"
      width="50%"
      center
      :before-close="closeDialogBrand"
    >
      <el-row style="padding: 20px;">
        <el-input v-model="brandKW">
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="openDialogBrand(brandKW)"
          ></el-button>
        </el-input>
      </el-row>
      <div class="brands-body">
        <el-col :span="12" v-for="item in brands" :key="item.id">
          <div
            class="brands-item"
            :class="{ on: item === selBrand }"
            @click="selOne(item)">
            {{ item.nameShow }}
          </div>
        </el-col>
      </div>
      <el-row class="text-warning">
        （温馨提示：请尽量输入准确关键字，以帮助您快速查找）
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBrand = false">取 消</el-button>
        <el-button type="primary" @click="brandsConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import eControl from "@/components/e-control";
import { getOrgTree, getListForManage, uploadMultipleFiles } from "@/api/admin.api";
import { deleteFile, removeByUrls,getFileUrl } from "@/api/common.api";
import {
  queryAuthorityBySupplierId,
  queryItemPropertiesList,
  saveOrUpdateProducts,
  getSupplierGoodsInfo,
  queryListByNameShow,
} from "@/api/supplier.api";
import { beforeUpload } from "@/util/common";
import { formOptions, btns } from "./control";
import columns from "./columns";
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
// 上传文件
import fileUpdata from "@/api/file.config";
import moment from "moment";
import { Base64 } from "js-base64";
import tools from "@/tools";

// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image"],
  ["clean"], // remove formatting button
];

export default {
  name: "local-supplier-commodity-management",
  components: {
    eControl,
    quillEditor,
  },
  props: {},
  data() {
    var checkNum = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error("不能输入负值"));
      }
      callback();
    };
    return {
      skuShow: false,
      goodsStockShow: false,
      goodsId: "",
      showFlag: false,
      propertiesHtml: "",
      goodsDescFileList: [],
      itemPropertiesList: [],
      loading: false,
      // 表格表头
      columns,
      // 表单配置项
      formOptions,
      searchLabelWidth: "100px",
      // 按钮组
      btns,
      // 提交表单数据
      formData: {
        goodsPropertyList: [],
        isImport: "国产",
        mainFiles: '',
        files: ''
      },
      // 表单校验
      formRules: {
        mainFiles: [
          { required: true, message: "请上传主要图片", trigger: "change" }
        ],
        files: [
          { required: true, message: "请上传一般图片", trigger: "change" }
        ],
        sku: [
          { required: true, message: "请输入商品编号sku", trigger: "blur" }
        ],
        typeNo: [
          { required: true, message: "请输入规格型号", trigger: "blur" }
        ],
        brandName: [
          { required: true, message: "请输入品牌名称", trigger: "change" }
        ],
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        isImport: [
          { required: true, message: "请输入进口标识", trigger: "blur" }
        ],
        goodsArea: [
          { required: true, message: "请输入生产地", trigger: "blur" }
        ],
        agreementPrice: [
          { required: true, message: "请输入市场价格", trigger: "blur" }
        ],
        initExcludeTaxPrice: [
          { required: true, message: "请输入未税价格", trigger: "blur" }
        ],
        taxRate: [
          { required: true, message: "请输入税率", trigger: "blur" }
        ],
        saleUnit: [
          { required: true, message: "请输入计量单位", trigger: "blur" }
        ],
        goodsStock: [
          { required: true, message: "请输入库存", trigger: "blur" }
        ],
        produceDate: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          }
        ],
        goodsWeight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ]
      },

      // 左侧树
      treeData: [],
      // 右侧树
      treeDataTable: [],
      // 树配置项
      initProps: {
        children: "children",
        label: "categoryName",
      },
      fileData: [],  // 文件上传数据（多文件合一）
      fileDataEditor: [],  // 富文本文件上传数据（多文件合一）
      // 上传一般图片数据
      fileList: [],
      // 上传主要图片数据
      mainFileList: [],
      // 编辑框是否展示
      editDialogShow: false,
      editDialogType: 0,
      // 编辑框表单数据
      dialogFormCurrent: {},
      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表格数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0,
      },
      // 表格选中数据
      tableSelectData: [],
      fileHeaders: {},
      fileUrl: "",
      treeExpanded: [], // 资源展开ID
      treeCheckeds: [], // 选择资源id
      resourceArray: [],
      treeList: [], //资源数据列表
      dataObjById: {},
      accreditKeys: [], // 授权资源ID
      dialogImageUrl: "",
      dialogVisible: false,
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: (value) => {
                if (value) {
                  document.querySelector(".uploadImage input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
              upload: (value) => {
                if (value) {
                  alert("自定义文件上传");
                }
              },
            },
          },
        },
      },
      // 选择品牌弹窗
      dialogBrand: false,
      // 品牌
      brands: [],
      // 品牌关键字
      brandKW: "",
      selBrand: "",
    }



  },
  filters: {
    formeTime(val) {
      return moment(val).format("YYYY-MM-DD hh:mm:ss");
    },
  },
  watch: {
    mainFileList(val) {
      this.$set(this.formData,'mainFiles',val.join(","))
    },
    fileList(val) {
      this.$set(this.formData,'files',val.join(","))
    }
  },
  computed: {
    // 组合查询条件和分页
    searchData() {
      const { pageNum, pageSize } = this.pageData;
      return { ...this.searchFormData, size: pageSize, current: pageNum };
      // return Object.assign(this.searchFormData,{size: pageSize},{current:pageNum})
    },
    // 表单实例
    dialogForm() {
      return this.$refs.dialogForm;
    },
    //表格最大高度
    tableMaxHeight() {
      return window.innerHeight - this.controlHeight - 160;
    },
    // 编辑框标题
    editDialogTitle() {
      return this.editDialogType === 0 ? "新增" : "编辑";
    },
    // 操作列自定义按钮
    operationBtn() {
      let btns;
      this.tableColumns.map((item) => {
        if (item.slotName === "operation") {
          btns = item.btns || [];
        }
      });
      return btns;
    },
  },
  methods: {
    // 获取组织树
    getOrgTreeEvent() {
      getOrgTree("0").then((res) => {
        this.treeData = this.treeDataTable = res;
      });
    },
    // 左侧树点击
    clickNode(obj, item, data) {
      if (item.level != 3) {
        return;
      }
      this.formData.goodsPropertyList.splice(0);
      // 查询商品目录属性列表
      var param = {
        current: 1,
        size: 1000,
      };
      // 一级分类Id
      this.formData.primaryCategory = item.parent.parent.data.id;
      this.formData.primaryCategoryName = item.parent.parent.data.categoryName;
      // 二级分类Id
      this.formData.secondaryCategory = item.parent.data.id;
      this.formData.secondaryCategoryName = item.parent.data.categoryName;
      // 三级分类Id
      this.formData.tertiaryCategory = obj.id;
      this.formData.tertiaryCategoryName = obj.categoryName;
      queryItemPropertiesList(obj.id, param).then((res) => {
        this.itemPropertiesList = res.records;
        console.log(this.itemPropertiesList);
        var len = this.itemPropertiesList.length;
        for (var i = 0; i < len; i++) {
          var pro = {
            key: res.records[i].propertyName,
            value: "",
          };
          this.formData.goodsPropertyList.push(pro);
        }
      });
    },
    // 初始化表格数据请求
    init() {
      this.quill = this.$refs.text.quill;
      let dom = this.quill.container;
      let bodyH = document.body.clientHeight;
      dom.style.height = 500 + "px";
      this.$refs.scroll.wrap.style.height = bodyH - "190" + "px";
      let goodsId = this.$route.query.id;
      if (goodsId != undefined) {
        this.goodsId = goodsId;
        // 查询回显商品详情
        this.initGoodsInfo();
      }
      // this.getOrgTreeEvent();
      this.getTableData();
    },
    initGoodsInfo() {
      var param = {
        id: this.goodsId,
      };
      getSupplierGoodsInfo(param).then((res) => {
        this.formData = res;
        this.skuShow = true;

        if (null !== res.goodsImagePath) {
          // 加载主图片
          const curFile = {
            name: "",
            url: res.goodsImagePath,
            id: "",
            fileType: 14,
          };
          this.mainFileList.push(curFile);
        }


        if (null !== res.goodsImageList) {
          // 加载一般图片
          res.goodsImageList.filter((path) => {
            const curGoodsFile = {
              name: "",
              url: path,
              id: "",
              fileType: 14,
            };
            this.fileList.push(curGoodsFile);
          });
        }

        if (this.$route.query.info == "info") {
          // 查看详情，不能编辑
          this.showFlag = true;
          this.goodsStockShow = true;
          return;
        }
        if (
          res.goodsState == "UNCOMMIT" ||
          res.goodsState == "RETURN" ||
          res.goodsState == "DOWN"
        ) {
          this.showFlag = false;
        } else {
          this.showFlag = true;
        }
      });
    },
    /**
     * @functionName searchControlHandle
     * @param {Object} data 查询参数
     * @description 查询
     * @author 张航
     * @date 2020-09-08 15:01:26
     * @version V1.0.0
     */
    searchControlHandle(data) {
      console.log(data);
      this.searchFormData = data;
      this.refreshPageCurrent();
    },
    /**
     * @functionName refreshControlHandle
     * @param {Object} data 重置后的数据
     * @description 重置查询条件
     * @author 张航
     * @date 2020-09-08 17:01:51
     * @version V1.0.0
     */
    refreshControlHandle(data) {
      console.log(data);
      this.searchFormData = data;
    },
    /**
     * @functionName changeControlHeight
     * @param {String} height 控制区占用高度
     * @description 控制区高度变化
     * @author 张航
     * @date 2020-09-16 16:17:07
     * @version V1.0.0
     */
    changeControlHeight(height) {
      this.controlHeight = height;
    },
    /**
     * @functionName insertControlHandle
     * @description 点击新增按钮
     * @author 张航
     * @date 2020-09-08 17:35:28
     * @version V1.0.0
     */
    insertControlHandle() {
      this.openDialog();
    },
    /**
     * @functionName deleteControlHandle
     * @description 点击删除按钮
     * @author 张航
     * @date 2020-09-08 17:38:28
     * @version V1.0.0
     */
    deleteControlHandle() {
      if (this.checkTableSelectData()) {
        const ids = [];
        this.tableSelectData.map((item) => {
          if (item && item.id) {
            ids.push(item.id);
          }
        });
        console.log(ids);
        this.deleteTableHandle({ id: ids });
      }
    },
    /**
     * @functionName changeTableSelectData
     * @param {Array} rows 选中数据
     * @description 表格选中数据改变
     * @author 张航
     * @date 2020-09-08 17:52:12
     * @version V1.0.0
     */
    changeTableSelectData(rows) {
      this.tableSelectData = rows;
    },
    /**
     * @functionName checkTableSelectData
     * @return {Number} 返回结果
     * @description 方法描述
     * @author 张航
     * @date 2020-09-10 09:58:59
     * @version V1.0.0
     */
    checkTableSelectData() {
      if (this.tableSelectData.length === 0) {
        this.$alert("至少选择一条数据！", "提示", {
          confirmButtonText: "确定",
        });
      }
      return this.tableSelectData.length;
    },
    /**
     * @functionName changePageSize
     * @param {Number} size 分页条数
     * @description 修改分页条数
     * @author 张航
     * @date 2020-09-08 17:57:06
     * @version V1.0.0
     */
    changePageSize(size) {
      this.pageData.pageSize = size;
      this.getTableData();
    },
    /**
     * @functionName changePageCurrent
     * @param {Number} current 当前分页
     * @description 修改当前分页
     * @author 张航
     * @date 2020-09-08 18:02:03
     * @version V1.0.0
     */
    changePageCurrent(current) {
      this.pageData.pageNum = current;
      this.getTableData();
    },
    /**
     * @functionName refreshPageCurrent
     * @description 重置当前分页
     * @author 张航
     * @date 2020-09-22 10:45:57
     * @version V1.0.0
     */
    refreshPageCurrent() {
      this.pageData.pageNum = 1;
      this.getTableData();
    },
    /**
     * @functionName getTableData
     * @description 获取表格数据
     * @author 张航
     * @date 2020-09-08 17:59:45
     * @version V1.0.0
     */
    getTableData() {
      queryAuthorityBySupplierId().then((res) => {
       // console.log(res);
        this.resourceArray = res;
      });
    },
    /**
     * @functionName updateTableHandle
     * @param {Object} row 当前行数据
     * @description 表格编辑按钮
     * @author 张航
     * @date 2020-09-14 16:43:26
     * @version V1.0.0
     */
    updateTableHandle(row) {
      console.log(row);
      this.dialogFormCurrent = { ...row };
      this.openDialog(1);
    },
    /**
     * @functionName deleteTableHandle
     * @param {Object} row 当前行数据
     * @description 表格删除按钮
     * @author 张航
     * @date 2020-09-14 17:17:06
     * @version V1.0.0
     */
    deleteTableHandle(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const { id } = row;
        const {
          delete: { url, type = "GET" },
        } = this.interFace;
        this.interFaceEvent(url, id, type).then((res) => {
          // TODO 根据接口调整处理逻辑
          // console.log(res);
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.refreshPageCurrent();
        });
      });
    },
    /**
     * @functionName openDialog
     * @param {Number} type 编辑框类型;0:新增;1:编辑;
     * @description 打开编辑框
     * @author 张航
     * @date 2020-09-08 11:38:51
     * @version V1.0.0
     */
    openDialog(type = 0) {
      this.editDialogType = type;
      this.editDialogShow = true;
    },
    /**
     * @functionName closeDialog
     * @description 关闭编辑框
     * @author 张航
     * @date 2020-09-08 14:27:02
     * @version V1.0.0
     */
    closeDialog() {
      this.editDialogType = 0;
      this.editDialogShow = false;
    },
    /**
     * @functionName saveDialogData
     * @description 保存弹框数据
     * @author 张航
     * @date 2020-09-08 18:15:14
     * @version V1.0.0
     */
    saveDialogDataHandle() {
      console.log(this.dialogForm.formData);
      const check = this.$refs["dialogForm"].handleValidate();
      if (!check) {
        this.$message({
          message: "请检查表单填写内容",
          type: "warning",
        });
        return check;
      }

      // 定义请求地址
      const _url =
        this.editDialogType === 0
          ? this.interFace.insert.url
          : this.interFace.update.url;
      // 定义请求类型
      const _type =
        this.editDialogType === 0
          ? this.interFace.insert.type
          : this.interFace.update.type;

      this.interFaceEvent(_url, this.dialogForm.formData, _type).then((res) => {
        // TODO 根据接口调整处理逻辑
        // console.log(res);
        this.dialogForm.handleRefresh();
        this.closeDialog();
        this.$message({
          message: "保存成功",
          type: "success",
        });
        this.refreshPageCurrent();
      });
    },
    /**
     * @functionName cancelDialogData
     * @description 取消保存弹框数据
     * @author 张航
     * @date 2020-09-08 18:17:11
     * @version V1.0.0
     */
    cancelDialogDataHandle() {
      this.dialogForm.handleRefresh();
      this.closeDialog();
    },
    /**
     * @functionName forwardEvent
     * @param {String} name 事件名称
     * @param {*} data 数据
     * @description 转发自定义事件
     * @author 张航
     * @date 2020-09-08 14:51:05
     * @version V1.0.0
     */
    forwardEvent(name, data) {
      this.$emit(name, data);
    },
    /**
     * @functionName interFaceEvent
     * @param {String|} url 请求地址
     * @param {Object} data 请求参数
     * @param {String} type 请求类型，默认为GET
     * @return {Promise} 返回结果
     * @description 接口访问
     * @author 张航
     * @date 2020-09-14 16:14:51
     * @version V1.0.0
     */
    interFaceEvent(url, data, type = "GET") {
      // let _url = url
      const _type = type.toLowerCase();
      // if (_type === 'get') {
      //   _url = _url + this.$tools.urlParam(data)
      // }
      return this.$api[_type](url, data);
    },
    /**
     * @description 上传的图片格式和大小
     * @author 穆宏宇
     * @date 2020-09-14 11:22:21
     * @param
     * @return
     * */
    beforeAvatarUpload(file) {
      const typeList = ["png", "jpg"];
      const isJPG = beforeUpload(file, typeList);
      const isLt5kb = file.size / 1024 < 500;
      if (!isJPG) {
        this.$message.error("上传文件格式不符合!");
      }
      if (!isLt5kb) {
        this.$message.error("上传图片大小不能超过 500kb!");
      }
      return isJPG && isLt5kb;
    },
    // 上传错误文件时提示
    handleAvatarError(res, file) {
      this.$message.error("文件上传失败，请重试");
    },
    mainHandleAvatarSuccess(res, file) {
      const curFile = {
        name: res.data.submittedFileName,
        url: res.data.url,
        id: res.data.id,
        fileType: res.data.fileType,
      };
      this.mainFileList.push(curFile);
      const ids = [];
      this.mainFileList.map((item) => {
        ids.push(item.id);
      });
      this.formData.mainAttachmentId = ids.toString();
    },
    /**
    * @functionName submitUploadEditor
    * @desccription 富文本批量上传图片
    * @author 穆宏宇
    * @date 2021-04-09 10:21:23
    * @version v1.0.0
    */
    submitUploadEditor() {
      if (this.fileDataEditor.length === 0) {
        this.$message({
          message: "请选择一般图片",
          type: 'warning'
        });
        return
      }
      if (this.goodsDescFileList.length + this.fileDataEditor.length > 10) {
        this.$message.warning(
          `最多可上传10张图片，您已超限`
        )
        return
      }
      const formData = new FormData();  // new formData对象
      this.$refs.upload.submit();  // 提交调用uploadFile函数
      formData.append('Authorization', tools.localRead('access_token'));  // 添加token
      this.fileDataEditor.forEach(item=>{
        formData.append("fileList", item.raw);
      })

      formData.append("fileType", 14);
      uploadMultipleFiles(formData).then(res=>{
        this.$message({
          message: "上传成功",
          type: 'success'
        });
        res.forEach(item=>{
          const {submittedFileName,id,url,fileType} = item
          // 获取光标所在位置
          let length = this.quill.getSelection().index;
          // 插入图片 res.url为服务器返回的图片地址
          this.quill.insertEmbed(length, "image", url);
          // 调整光标到最后
          this.quill.setSelection(length + 1);
          // this.goodsDescFileList.push({name: submittedFileName, id, url, fileType})
        })
        this.goodsDescFileList = [];
        this.fileDataEditor = []
      })
    },
    submitUpload() {
      if (this.fileData.length === 0) {
        this.$message({
          message: "请选择一般图片",
          type: 'warning'
        });
        return
      }
      if (this.fileList.length + this.fileData.length > 10) {
        this.$message.warning(
          `最多可上传10张图片，您已超限`
        )
        return
      }
      const formData = new FormData();  // new formData对象
      this.$refs.upload.submit();  // 提交调用uploadFile函数
      formData.append('Authorization', tools.localRead('access_token'));  // 添加token
      this.fileData.forEach(item=>{
        formData.append("fileList", item.raw);
      })

      formData.append("fileType", 14);
      uploadMultipleFiles(formData).then(res=>{
        this.$message({
          message: "上传成功",
          type: 'success'
        });
        res.forEach(item=>{
          const {submittedFileName,id,url,fileType} = item
          this.fileList.push({name: submittedFileName, id, url, fileType})
        })
        this.fileData = []
      })
    },
    // 上传文件
    uploadFile(file,fileList) {
      // console.log({file,fileList});
      // this.fileData.push(file.file);  // append增加数据
    },
    //监控上传文件列表
    handleChange(file, fileList) {
      this.fileData.push(file)
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log(fileList)
      const {submittedFileName,id,url,fileType} = res.data;
      this.fileList.push({name: submittedFileName, id, url, fileType})
      const ids = [];
      this.fileList.map((item) => {
        ids.push(item.id);
      });
      this.formData.attachmentId = ids.toString();
    },
    // 预览附件
    handlePreview(file) {
      console.log('预览',file);
      if (file.response && file.response.data) {
        const {fileType,id} = file.response.data
        file['fileType'] = fileType
        file['id'] = id
      }
      getFileUrl(file.fileType,file.id).then(res=>{
        this.dialogImageUrl = res
        this.dialogVisible = true
      })
    },
    // 取消上传图片
    mainHandleRemove(file, fileList) {
      if (file && file.status === "success") {
        const data = {
          urls: [file.url],
        };
        removeByUrls(data).then((res) => {
          const index = this.mainFileList.findIndex(item => item.url === file.url);
          this.mainFileList.splice(index, 1);
        });
      }
    },
    handleRemove(file, fileList) {
      const index = this.fileList.findIndex(item => item.uid === file.uid);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
      const dataIndex = this.fileData.findIndex(item => item.uid === file.uid);
      if (dataIndex > -1) {
        this.fileData.splice(dataIndex,1);
      }
    },
    editorHandleRemove(file, fileList) {
      // console.log({file, fileList})
      // this.fileDataEditor = this.fileDataEditor.filter(item=>item.uid != )
      // this.goodsDescFileList = this.goodsDescFileList.filter(item=>item.url !== file.url)
    },
    // 选中上传图片限制
    handleExceed1(files, fileList) {
      this.$message.warning(
        `最多可上传1张图片，您已超限`
      )
    },
    handleExceed10(files, fileList) {
      this.$message.warning(
        `最多可上传10张图片，您已超限`
      )
    },

    // 移除上传图片
    beforeRemove(file, fileList) {
      if (file && file.status === "success") {
        return this.$confirm(`确定移除 ${file.name}？`);
      }

    },
    /**
     * @description 递归转树型
     * @author 穆宏宇
     * @date 2020-09-28 10:40:59
     * @param data 树型列表
     * @param defaultRoot 0/null 为跟节点
     * @param parent 父节点
     * @return
     * */
    getTreeData2(data, parent = []) {
      let self = this;
      var tree = [];
      var temp;
      // 遍历数组，通过parentId，获取父节点对象，如果不存在，则为根节点
      data.map((item) => {
        if (item.parentCategoryId == undefined) {
          item.parentCategoryId = "0";
        }
        if (parent.indexOf(item.parentCategoryId) > -1) {
          temp = self.getTreeData2(data, [item.id]);
          // 插入子节点数组children
          if (temp.length > 0) {
            item.children = temp;
          } else {
            item.children = [];
          }
          // 插入父节点对象parent
          if (self.dataObjById[item.parentId]) {
            let { id, label, parentId } = self.dataObjById[item.id];
            item.parent = { id, label, parentId };
          } else {
            item.parent = {};
          }
          tree.push(item);
        }
      });
      return tree;
    },
    /**
    * @desccription 富文本批量选择图片改变后
    * @author 穆宏宇
    * @date 2021-04-09 10:32:51
    * @version v1.0.0
    */
    editorHandleChange(file, fileList) {
      this.fileDataEditor = fileList
    },
    // 上传成功
    handleImgSuccess(res) {
      if (res && res.code === 0) {
        // 获取光标所在位置
        let length = this.quill.getSelection().index;
        // 插入图片 res.url为服务器返回的图片地址
        this.quill.insertEmbed(length, "image", res.data.url);
        // 调整光标到最后
        this.quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      this.goodsDescFileList = [];
      this.loading = false;
    },
    //  上传失败
    handleImgError(err) {
      this.$message.error("图片插入失败");
      this.loading = false;
    },
    // 保存
    saveOrUpdateProducts() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
        if (this.formData.tertiaryCategory == undefined) {
          this.$message({
            message: "请选择商品目录，并完成主属性填写",
            type: "error",
          });
          return;
      }
      if (null !== this.formData.goodsPropertyList) {
        var items = this.formData.goodsPropertyList.filter(item =>item.value.trim() == '');
        if(items.length > 0){
          this.$message({
            message: "请完成主属性填写",
            type: "error",
          });
          return;
        }
        this.$set(this.formData,'goodsPropertyList',items);
      }


      let data = this.formData;
      const filter = this.$options.filters["formeTime"];
      data.produceDate = filter(data.produceDate);
      data.goodsImagePath = this.mainFileList[0].url;
      // data.goodsProperty = JSON.stringify(this.formData.goodsProperty);
      const urls = [];
      this.fileList.map((item) => {
        urls.push(item.url);
      });
      // data.goodsImageList = urls.toString();
      data.goodsImageList = urls;
      saveOrUpdateProducts(data)
        .then((res) => {
          this.mainFileList = []
          this.fileList = []
          this.fileDataEditor = []
          this.fileData = []
          this.$message.success("保存成功！");
          this.$router.push("/supplier-commerce-putawayt");
        })
        .catch((err) => {
          console.log(err);
          this.$message({
            message: "保存失败！",
            type: "error",
          });
        });
        }
      });
    },
    submitProducts() {
      this.formData.isCommit = true;
      this.saveOrUpdateProducts();
    },
    // 打开品牌弹窗
    openDialogBrand(nameShow = "", open = false) {
      const pamars = {
        nameShow,
        current: 1,
        size: 20,
      };
      queryListByNameShow(pamars).then((res) => {
        const list = res.records
        this.brands = list.filter(item=>item.nameShow);
        if (open) {
          this.dialogBrand = true;
        }
      });
    },
    // 关闭品牌弹窗
    closeDialogBrand() {
      this.dialogBrand = false;
      this.brands = [];
      this.selBrand = {};
      this.brandKW = "";
    },
    // 选中一个品牌
    selOne(item) {
      this.selBrand = item;
    },
    // 确定
    brandsConfirm() {
      if (this.selBrand.id) {
        // this.formData.brandName = this.selBrand.nameShow;
        this.$set(this.formData,'brandName',this.selBrand.nameShow)
        this.formData.brandId = this.selBrand.id;
        this.closeDialogBrand();
      } else {
        this.$alert("请先选择一个品牌！", "提示", {
          confirmButtonText: "确定",
        });
      }
    },
  },
  created() {
  },
  mounted() {
    this.fileHeaders = { ...fileUpdata.headers() };
    this.fileUrl = fileUpdata.url;
    this.init();
  },
};
</script>
<style lang="scss" scoped>
.goodsDesc {
  height: 300px;
  .uploadImage {
    display: none;
  }
  .btn {
    margin-top: 10px;
    text-align: center;
  }
}
.produce-date.el-date-editor.el-input {
  width: 206px;
}
.putawayt-action {
  padding-top: 10px;
  border-top: 1px solid #dcdcdc;
  text-align: center;
}
.brands-body {
  display: flex;
  flex-wrap: wrap;
  .brands-item {
    padding: 10px 20px;
    border-radius: 4px;
    -moz-box-sizing: border-box;  /*Firefox3.5+*/
    -webkit-box-sizing: border-box; /*Safari3.2+*/
    -o-box-sizing: border-box; /*Opera9.6*/
    -ms-box-sizing: border-box; /*IE8*/
    box-sizing: border-box; /*W3C标准(IE9+，Safari5.1+,Chrome10.0+,Opera10.6+都符合box-sizing的w3c标准语法)*/
    &:hover {
      background: #f5f7fa;
    }
    &.on {
      background: $--color-primary;
      color: #fff;
    }
  }
}
.text-warning {
  text-align: center;
  color: $--color-warning;
  font-size: 12px;
}

</style>
<style lang="scss">
  .limited .el-upload{
    display: none;
  }
</style>
